package com.kebaijia.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author luoy
 * @date 2018/7/24 0024 下午 8:32
 * @Description: ${todo}
 */
public class AioClient {

    public static void main(String[] args) throws IOException, InterruptedException {
        AsynchronousSocketChannel client = AsynchronousSocketChannel.open();

        client.connect(new InetSocketAddress("localhost", 9000), null, new CompletionHandler<Void, Object>() {

            @Override
            public void completed(Void result, Object attachment) {
                try {
                    System.out.println("连接服务器成功");
                    ByteBuffer buffer = ByteBuffer.allocate(20);

                    Future<Integer> future = client.read(buffer);

                    future.get();

                    //有写模式到读模式
                    buffer.flip();

                    String gbk = Charset.forName("GBK").decode(buffer).toString();
                    System.out.println(gbk);
                    client.close();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void failed(Throwable exc, Object attachment) {

            }
        });

        Thread.sleep(6000);
    }
}
